package Ginit

import (
	"fmt"
	config2 "gin-demo/config"
	"gin-demo/container"
	"gin-demo/entity"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"os"
)

func Main() {
	logInit()
	config2.InitConfig()
	DBInit()

}

func logInit() {
	// 加载日志
	log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
}

func DBInit() {
	config := container.Get("config").(config2.Config)
	//gorm
	mysqlArgs := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
		config.Mysql.User, config.Mysql.Password, config.Mysql.Host, config.Mysql.Port, config.Mysql.Database)
	db, err := gorm.Open(mysql.Open(mysqlArgs), &gorm.Config{})

	if err != nil {
		panic("gorm open mysql failed")
		return
	}
	err = db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&entity.Test{})
	if err != nil {
		panic("创建表失败")
	}
	sqlDB, _ := db.DB()
	sqlDB.SetMaxIdleConns(10)  //空闲连接数
	sqlDB.SetMaxOpenConns(100) //最大连接数
	container.Add("db", db)
}
